<?php
class PostService extends BaseDbService
{
	public function __construct()
	{
		$this->dao				= new PostDao();
	}
	
	public function get($id,$tag=true)
	{
		$info	= $this->dao->get($id);
		if(!$info)
		{
			return false;
		}
		$info['content']	= json_decode($info['content'],true);
		if($tag)
		{
			$tags	= $this->getPostTags($id);
			if(!empty($tags))
			{
				$tmp	= array();
				foreach($tags as $v)
				{
					$tmp[]	= $v['name'];
				}
				$info['tag']	= implode(',',$tmp);
				$info['tags']	= $tags;
			}
		}
		return $info;
	}
	
	public function add($data)
	{
		if(array_key_exists('content',$data))
		{
			$data['content']	= json_encode($data['content']);
		}
		$id	= $this->dao->add($data);
		//添加标签
		if($id>0)
		{
			if(array_key_exists('tag',$data))
			{
				//添加新的标签
				$this->addTags($id,$data['tag']);
			}
		}
		return $id;
	}
	
	public function update($id,$data)
	{
		if(array_key_exists('content',$data))
		{
			$info	= $this->get($id);
			if($info)
			{
				foreach($info['content'] as $k=>$v)
				{
					if(!array_key_exists($k,$data['content']))
					{
						$data['content'][$k]	= $v;
					}
				}
			}
			
			$data['content']	= json_encode($data['content']);
		}
		if(array_key_exists('tag',$data))
		{
			//删除旧的标签
			$this->delPostTags($id);
			//添加新的标签
			$this->addTags($id,$data['tag']);
		}
		return $this->dao->update($id,$data);
	}
	
	public function del($id)
	{
		$this->delPostTags($id);
		return parent::del($id);
	}
	
	public function deleteByIds($ids)
	{
		foreach($ids as $id)
		{
			$this->delPostTags($id);
		}
		$idSql	= $this->getInSql($ids);
		$condition['expression']	= 'id in('.$idSql.')';
		return parent::deleteRows($condition);
	}
	
	private function getPostTags($id)
	{
		$ret	= false;
		$trDao	= new TagRelatedDao();
		$condition['where']['expression']		= 'info_id=:info_id and type=1';
		$condition['where']['value']['info_id']	= $id;
		$tmp	= $trDao->fetchRows($condition);
		if(!empty($tmp))
		{
			$tagIds	= array();
			foreach($tmp as $v)
			{
				$tagIds[]	= $v['tag_id'];
			}
			$idSql	= $this->getInSql($tagIds);
			$con['where']['expression']	= 'id in('.$idSql.')';
			$tagDao	= new TagDao();
			$ret	= $tagDao->fetchRows($con);
		}
		return $ret;
	}
	
	private function delPostTags($id)
	{
		$trDao	= new TagRelatedDao();
		$condition['expression']		= 'info_id=:info_id and type=1';
		$condition['value']['info_id']	= $id;
		return $trDao->deleteRows($condition);
	}
	
	private function addTags($id,$tags)
	{
		$tags	= trim($tags);
		if(empty($tags))
		{
			return;
		}
		$tags	= str_replace('，',',',$tags);
		$tags	= explode(',',$tags);
		$tagDao	= new TagDao();
		$trDao	= new TagRelatedDao();
		foreach($tags as $tag)
		{
			$tagInfo	= $tagDao->getByName($tag);
			if(!$tagInfo)
			{
				$tagId	= $tagDao->add(array('name'=>$tag));
			}
			else
			{
				$tagId	= $tagInfo['id'];
			}
			if($tagId)
			{
				$trDao->add(array('info_id'=>$id,'type'=>1,'tag_id'=>$tagId));
			}
		}
	}
	
	public function getList($con,$orderby,$start,$num,$fields='',$cache=0,$position='')
	{
		//从缓存中获取
		$cacheId		= md5(serialize($con).$orderby.$start.$num.$fields.$cache.$position);
		if($cache>0)
		{
			$result	= $this->getDataFromCache($cacheId);
			if($result)
			{
				return $result;
			}
		}
		
		if(!array_key_exists('tag_id',$con))
		{
			$result	= parent::getList($con,$orderby,$start,$num,$fields);
		}
		else
		{
			//查询tag和文章关联表
			$trDao	= new TagRelatedDao();
			$condition['where']['expression']		= 'tag_id=:tag_id and type=1';
			$condition['where']['value']['tag_id']	= $con['tag_id'];
			
			$result['count']	= $trDao->count($condition);
			if($result['count']>0)
			{
				if($num>0)
				{
					$condition['limit'] 	= $num;
				}
				if($start>=0)
				{
					$condition['offset'] 	= $start;
				}
				$condition['orderby'] 		= 'info_id DESC';
				$condition['fields']		= 'info_id';
				$tagRelates 				= $trDao->fetchRows($condition);
				
				if($tagRelates)
				{
					$ids	= array();
					foreach($tagRelates as $tv)
					{
						$ids[]	= $tv['info_id'];
					}
					$condition	= array();
					$condition['where']['expression']	= 'id in('.$this->getInSql($ids).')';
					$condition['orderby'] 		= 'id DESC';
					if($fields!='')
					{
						$condition['fields']	= $fields;
					}
					$result['rows'] 			= $this->dao->fetchRows($condition);
				}
			}
		}
		
		if($result['rows'])
		{
			foreach($result['rows'] as &$rv)
			{
				$rv['content']	= json_decode($rv['content'],true);
			}
		}
		//更新cache
		if($cache>0 && $result && !empty($result['rows']))
		{
			$this->saveDataToCache($cacheId,$result,$cache);
		}
		return $result;
	}
	
	public function addVisitNum($id,$add)
	{
		return $this->dao->addVisitNum($id,$add);
	}
	
	public function saveRemoteImage($content)
	{
		if(!preg_match_all("/src=[\"|'|\s]{0,}(http:\/\/([^>]*)\.(gif|jpg|png))/isU",$content,$m))
		{
			return $content;
		}
		$baseHost 	= "http://".$_SERVER["HTTP_HOST"];
		$m 			= array_unique($m[1]);
		$cf			= C('CommonFunction');
		foreach($m as $k=>$v)
		{
			//本地图片跳过
			if(eregi($baseHost,$v))
			{
				continue;
			}
			//相对路径的跳过
			if(!eregi("^http://",$v))
			{
				continue;
			}
			$img		= file_get_contents($v);
			$ext		= $cf->getFileExt($v);
			$name		= time().$cf->random(4).'.'.$ext;
			$newFile	= $cf->getUploadImagePath($name);
			$imgUrl		= $cf->getUploadImageUrl($name);
			$ret		= $cf->saveFile($newFile,$img);
			if($ret)
			{
				//替换内容中的图片地址
				$content = str_replace($v,$imgUrl,$content);
			}
		}
		return $content;
	}
	
	public function deleteLink($content)
	{
		$baseHost 	= "http://".$_SERVER['HTTP_HOST'];
		$content 	= str_replace($basehost,'#piscesbasehost#',$content);
		$content 	= preg_replace("/(<a[^>]+?href=[\"']{0,}http:\/\/[^\/]([^>]*)>)|(<\/a>)/isU","",$content);
		$content 	= str_replace('#piscesbasehost#',$baseHost,$content);
		
		return $content;
	}
	
	public function GetImageFromContent($content)
	{
		if(!preg_match_all("/(src)=[\"|'| ]{0,}([^>]*\.(gif|jpg|bmp|png))/isU",$content,$m))
		{
			return '';
		}
		$pic	= '';
		$m 		= array_unique($m[2]);
		if(count($m)>0)
		{
			$pic 	= preg_replace("/[\"|'| ]{1,}/", '', $m[0]);
		}
		return $pic;
	}
	
	private function getDataFromCache($id)
	{
		$cache 	= new LtCache();
		$cache->init();
		$ch 	= $cache->getTDG(C('LtConfig')->get('db.table.prefix')."post".$id);
		
		$result	= $ch->get('list');
		return $result;
	}
	
	private function saveDataToCache($id,$data,$ttl)
	{
		$cache 	= new LtCache();
		$cache->init();
		$ch 	= $cache->getTDG(C('LtConfig')->get('db.table.prefix')."post".$id);
		
		$tmp	= $ch->get('list');
		if($tmp!==false)
		{
			$ch->update('list',$data,$ttl);
		}
		else
		{
			$ch->add('list',$data,$ttl);
		}
	}
}
?>